//
//  ViewController.m
//  LMLabelSelect
//
//  Created by LM on 2022/11/4.
//

#import "ViewController.h"
#import "LMLabelSelectView.h"
#import "LMBaseTableView.h"
#import "LMTableViewCellModel.h"
#import "UIColor+Theme.h"
#import "LMWebTableViewCell.h"
#import "LMContentTableViewCell.h"
#import "MJExtension.h"
#import <AFNetworking/AFNetworking.h>

#define WS(weakself) __weak typeof (self) weakself = self;

#define KSCREENW [UIScreen mainScreen].bounds.size.width
#define KSCREENH [UIScreen mainScreen].bounds.size.height

@interface ViewController ()<WkwebViewHeightDelegate>
@property (strong, nonatomic) LMLabelSelectView *selectView;
@property (strong, nonatomic) LMBaseTableView *tableView;
@property (assign, nonatomic) BOOL isScroll; // 是否滚动
@property (strong, nonatomic) NSMutableArray *array;
@property (strong, nonatomic) NSMutableArray *dataArray;
@property (assign, nonatomic) CGFloat collectionWidth;
@end

@implementation ViewController


- (void)initBaseData{
    self.collectionWidth = 0;
    self.isScroll = NO;
    // 标签栏数据
    self.array = [NSMutableArray array];
    self.dataArray = [NSMutableArray array];
  
    self.view.backgroundColor = [UIColor whiteColor];
}

- (void)initUI{
    [self.view addSubview:self.selectView];
    self.selectView.frame = CGRectMake(0, 20, KSCREENW, 45);
    [self.view addSubview:self.tableView];
    self.tableView.frame = CGRectMake(0, CGRectGetMaxY(self.selectView.frame), KSCREENW, KSCREENH-45-20);
    
}

- (void)displayData{
    NSError* error = nil;
    
    NSString *json = [[NSBundle mainBundle] pathForResource:@"tableViewData" ofType:@"json"];
    NSData *jSONData = [NSData dataWithContentsOfFile:json];
    NSDictionary *dictFromData = [NSJSONSerialization JSONObjectWithData:jSONData
                                                           options:NSJSONReadingAllowFragments
                                                                   error:&error];
    NSArray *items = dictFromData[@"data"];
    
    // cell数据源
    for (int j=0; j<items.count; j++) {
        
        NSDictionary *dict = [items objectAtIndex:j];
        
        // 标签
        UIFont *font = font = [UIFont fontWithName:@"PingFangSC-Semibold" size:17];
        CGFloat width = [dict[@"name"] boundingRectWithSize:CGSizeMake(CGFLOAT_MAX, 45) options:NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName:font} context:nil].size.width+10;
        self.collectionWidth += width;
        LMLabelSelectModel *item = [[LMLabelSelectModel alloc]init];
        item.bId = [NSString stringWithFormat:@"%d",j];
        item.text = dict[@"name"];
        item.width = width;
        item.textColor = @"#888888";
        item.textOpacity = 100;
        item.choseTextColor = @"#FF3939";
        item.bgColor = @"#FFFFFF";
        item.choseTextFont = 18;
        item.textFont = 15;
        item.isSelected =  0 == j ? YES:NO;
        item.lineColor = @"#666666";
        [self.array addObject:item];
        
        
        NSInteger type = [dict[@"type"]integerValue];
        switch (type) {
            case 1:{
                
                LMTableViewCellModel *model = [LMTableViewCellModel mj_objectWithKeyValues:dict];
                LMContentTableViewCellModel *cell1 = [[LMContentTableViewCellModel alloc]init];
                cell1.model = model;
                [self.dataArray addObject:cell1];
            }
                break;
            case 2:{
                
                LMWebCellModel* model = [LMWebCellModel mj_objectWithKeyValues:dict];
                LMWebTableViewCellModel *cell1 = [[LMWebTableViewCellModel alloc]init];
                cell1.model = model;
                [self.dataArray addObject:cell1];
            }
                break;
            default:
                break;
        }
        
    }
    
    if (self.array.count < 4){
        self.selectView.frame = CGRectMake((KSCREENW-self.collectionWidth-(self.array.count-1)*10)/2, 20, self.collectionWidth+(self.array.count-1)*10, 45);
    }
    
     [self.selectView loadDataWithTitles:self.array];

    [self.tableView reloadData];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self initBaseData];

    [self initUI];
  
    [self displayData];

}

 // wkwebView代理
- (void)getWkWebViewHeight:(CGFloat)height{
    [self.tableView reloadData];
}

- (LMLabelSelectView*)selectView{
    WS(weakself);
    if (!_selectView){
        _selectView = [[LMLabelSelectView alloc]initWithFrame:CGRectZero];
        _selectView.scrollBlock = ^(NSInteger index, BOOL isDidCell) {
            if (isDidCell){
                weakself.isScroll = NO;
                [weakself.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:index] atScrollPosition:UITableViewScrollPositionTop animated:YES];

            }
        };
    }
    return _selectView;
}


- (LMBaseTableView*)tableView{
    WS(weakself);
    if (!_tableView){
        _tableView = [[LMBaseTableView alloc]initWithFrame:CGRectZero andStyle:UITableViewStyleGrouped];
        _tableView.estimatedSectionHeaderHeight = 0;
        _tableView.estimatedSectionFooterHeight = 0;
        _tableView.backgroundColor = [UIColor whiteColor];
        
        if (@available(iOS 15.0, *)) {
            _tableView.sectionHeaderTopPadding = 0;
        }

        [_tableView registerClass:[LMContentTableViewCell class] forCellReuseIdentifier:@"LMContentTableViewCell"];
        [_tableView registerClass:[LMWebTableViewCell class] forCellReuseIdentifier:@"LMWebTableViewCell"];
        
        _tableView.numberOfRowsBlock = ^NSInteger(UITableView *tableView, NSInteger section) {
            if (weakself.dataArray.count){
                id<LMViewModelProtocol> viewModel = [weakself.dataArray objectAtIndex:section];
                if ([viewModel isKindOfClass:[LMContentTableViewCellModel class]]){
                    LMContentTableViewCellModel *model = (LMContentTableViewCellModel*)viewModel;
                    return model.model.items.count;
                }else{
                    return 1;
                }
            }else{
                return 0;
            }
        };
        _tableView.cellForRowBlock = ^UITableViewCell *(UITableView *tableView, NSIndexPath *indexPath) {
            
            id<LMViewModelProtocol> viewModel = [weakself.dataArray objectAtIndex:indexPath.section];
            id<LMViewProtocol> cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([viewModel viewClass]) forIndexPath:indexPath];
            
            if ([cell isKindOfClass:[LMWebTableViewCell class]]){
                LMWebTableViewCell *webCell = (LMWebTableViewCell*)cell;
                webCell.delegate = weakself;
            }
            
            
            [cell setModel:viewModel Index:indexPath.row];
            UITableViewCell *tableCell = (UITableViewCell*)cell;
            if (!tableCell){
                tableCell = [[UITableViewCell alloc]init];
            }
            return tableCell;
        };
        _tableView.numberOfSectionsBlock = ^NSInteger(UITableView * _Nonnull tableView) {
            return weakself.dataArray.count;
        };
        
        _tableView.heightForRowBlock = ^CGFloat(UITableView * _Nonnull tableView, NSIndexPath * _Nonnull indexPath) {
            id<LMViewModelProtocol> viewModel = [weakself.dataArray objectAtIndex:indexPath.section];
            return [viewModel viewHeight];
        };
        _tableView.heightForSectionHeaderBlock = ^NSInteger(UITableView * _Nonnull tableView, NSInteger section) {
            return 40;
        };
        
        _tableView.viewForSectionHeaderBlock = ^UIView *(UITableView * _Nonnull tableView, NSInteger section) {
            
            UIView *sectionView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, KSCREENW, 40)];
            sectionView.backgroundColor = [UIColor colorWithHexString:@"#F1F1F1"];
            
            UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(10, 0, KSCREENW, 40)];
            LMLabelSelectModel *selectModel = weakself.array[section];
            label.text = selectModel.text;
            label.textColor = [UIColor redColor];
            [sectionView addSubview:label];
            return sectionView;
        };
        
        _tableView.scrollViewWillBeginDragging = ^(UIScrollView * _Nonnull scrollView) {
            weakself.isScroll = YES;
        };
        
        _tableView.scrollViewDidScroll = ^(UIScrollView * _Nonnull scrollView) {
            if (weakself.isScroll){
                if (scrollView == weakself.tableView) {
                    // 找到屏幕上cell的首个
                    NSArray *cellArray = [weakself.tableView visibleCells];
                    UITableViewCell *cell = [cellArray firstObject];
                    NSIndexPath *indexPath = [weakself.tableView indexPathForCell:cell];
                    NSInteger index = indexPath.section;
                    id<LMViewModelProtocol> cellModel = weakself.dataArray[index];
                    LMLabelSelectModel *obj = weakself.array[index];
                    if ([cellModel isKindOfClass:[LMContentTableViewCellModel class]]){
                        LMContentTableViewCellModel *contentModel = (LMContentTableViewCellModel*)cellModel;
                            if ([contentModel.model.tId isEqualToString:obj.bId]){
                                // 过滤重复数据
                                if (![obj.bId isEqualToString:weakself.selectView.lastModel.bId]){
                                    NSLog(@"%ld",index);
                                    [weakself.selectView moveScrollViewWithIndex:index isDidCell:NO];
                                }
                            }
                    }else if ([cellModel isKindOfClass:[LMWebTableViewCellModel class]]){
                        LMWebTableViewCellModel *webModel = (LMWebTableViewCellModel*)cellModel;
                            if ([webModel.model.tId isEqualToString:obj.bId]){
                                // 过滤重复数据
                                if (![obj.bId isEqualToString:weakself.selectView.lastModel.bId]){
                                    NSLog(@"%ld",index);
                                    [weakself.selectView moveScrollViewWithIndex:index isDidCell:NO];
                                }
                            }
                    }

                }
            }
        };
    }
    return _tableView;
}

@end
